package com.huhao.smark;

import static android.content.Context.MODE_PRIVATE;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.core.content.ContextCompat;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.android.material.imageview.ShapeableImageView;

import org.json.JSONObject;
import org.json.JSONException;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Calendar;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import static com.huhao.smark.Config.*;

public class PersonalFragment extends Fragment implements SharedPreferences.OnSharedPreferenceChangeListener {

    private GridLayout calendarGrid;
    private ImageButton btnPrevMonth, btnNextMonth;
    private TextView tvMonthYear;
    private LinearLayout activityContainer;
    private LinearLayout loginReminderContainer;
    private TextView loginReminderText;
    private View loginButtonPersonal;
    private SharedPreferences sharedPreferences;
    private boolean isLoggedIn = false;
    private String userAccount = "";
    private JSONObject calendarData;
    private OkHttpClient client;
    private SwipeRefreshLayout swipeRefreshLayout;
    private ShapeableImageView profile_avatar;
    private TextView profile_username;
    private TextView bookCountView;
    private int currentYear, currentMonth, bookCount;
    private String username = "";
    private TextView AccountView;
    private static final String API_URL = HTTP + IP + PORT + USER_INFO + "/"; // 替换为实际API地址

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_personal, container, false);

        // 初始化组件
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
        calendarGrid = view.findViewById(R.id.calendar_grid);
        btnPrevMonth = view.findViewById(R.id.btn_prev_month);
        btnNextMonth = view.findViewById(R.id.btn_next_month);
        tvMonthYear = view.findViewById(R.id.tv_month_year);
        activityContainer = view.findViewById(R.id.activity_container);
        loginReminderContainer = view.findViewById(R.id.login_reminder_container);
        loginReminderText = view.findViewById(R.id.login_reminder_text);
        loginButtonPersonal = view.findViewById(R.id.login_button_personal);

        bookCountView = view.findViewById(R.id.bookCount);
        profile_avatar = view.findViewById(R.id.profile_avatar);
        profile_username = view.findViewById(R.id.profile_username);
        AccountView = view.findViewById(R.id.account);

        // 初始化SharedPreferences
        sharedPreferences = requireActivity().getSharedPreferences("app_prefs", MODE_PRIVATE);
        isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
        userAccount = sharedPreferences.getString("account", "");
        bookCount = sharedPreferences.getInt("bookCount", 0);
        username = sharedPreferences.getString("username", "");
        sharedPreferences.registerOnSharedPreferenceChangeListener(this);

        // 初始化OkHttpClient
        client = new OkHttpClient();

        // 设置下拉刷新的监听器
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (isLoggedIn) {
                    loadCalendarDataFromJson();
                    updateCalendarDisplay();
                    loadUserInfoFromAPI();
                }
                swipeRefreshLayout.setRefreshing(false); // 停止刷新动画
                Toast.makeText(getContext(), "数据已刷新", Toast.LENGTH_SHORT).show();
            }
        });

        // 根据登录状态更新UI
        updateUIBasedOnLoginStatus();

        // 设置登录按钮点击事件
        loginButtonPersonal.setOnClickListener(v -> {
            Intent intent = new Intent(getContext(), LoginActivity.class);
            startActivity(intent);
        });

        // 如果已登录，加载用户信息
        if (isLoggedIn) {
            loadUserInfoFromAPI();
        }

        return view;
    }

    private void loadUserInfoFromAPI() {
        // 获取Token
        String token = sharedPreferences.getString("token", "");
        if (token.isEmpty()) {
            Log.e("PersonalFragment", "Token为空，无法请求用户信息");
            return;
        }

        // 构建请求
        String url = API_URL + userAccount;
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + token)
                .build();

        // 发送请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("PersonalFragment", "请求失败", e);
                showErrorToast("网络请求失败，请检查网络连接");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    Log.e("PersonalFragment", "响应错误: " + response.code());
                    showErrorToast("获取用户信息失败，状态码: " + response.code());
                    return;
                }

                // 解析响应
                String responseData = response.body().string();
                try {
                    JSONObject jsonResponse = new JSONObject(responseData);
                    int code = jsonResponse.optInt("code");
                    boolean success = jsonResponse.optBoolean("success", false);

                    if (code == 200 && success) {
                        JSONObject data = jsonResponse.optJSONObject("data");

                        // 提取用户信息
                        String newAccount = data.optString("account");
                        String newUsername = data.optString("username");
                        int newBookCount = data.optInt("bookCount");

                        // 更新本地存储
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putString("account", newAccount);
                        editor.putString("username", newUsername);
                        editor.putInt("bookCount", newBookCount);
                        editor.apply();

                        // 更新UI
                        updateUserInfoUI(newAccount, newUsername, newBookCount);
                    } else {
                        String errorMsg = jsonResponse.optString("message", "未知错误");
                        Log.e("PersonalFragment", "API错误: " + errorMsg);
                        showErrorToast("获取用户信息失败: " + errorMsg);
                    }
                } catch (JSONException e) {
                    Log.e("PersonalFragment", "JSON解析错误", e);
                    showErrorToast("数据解析错误");
                }
            }
        });
    }

    private void showErrorToast(final String message) {
        requireActivity().runOnUiThread(() -> {
            Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
        });
    }

    private void updateUserInfoUI(final String account, final String username, final int bookCount) {
        requireActivity().runOnUiThread(() -> {
            this.userAccount = account;
            this.username = username;
            this.bookCount = bookCount;

            updateUIBasedOnLoginStatus();
        });
    }

    private void updateUIBasedOnLoginStatus() {
        if (isLoggedIn) {
            activityContainer.setVisibility(View.VISIBLE);
            profile_avatar.setVisibility(View.VISIBLE);
            profile_username.setVisibility(View.VISIBLE);
            loginReminderContainer.setVisibility(View.GONE);

            // 更新用户信息
            bookCountView.setText("记账总次数：" + bookCount);
            profile_username.setText(username);
            AccountView.setText(userAccount);

            // 加载日历数据
            loadCalendarDataFromJson();
            updateCalendarDisplay();
        } else {
            activityContainer.setVisibility(View.GONE);
            profile_avatar.setVisibility(View.GONE);
            profile_username.setVisibility(View.GONE);
            loginReminderContainer.setVisibility(View.VISIBLE);

            bookCountView.setText("记账总次数：NaN");
            profile_username.setText("");
            AccountView.setText("");
        }
    }

    private void loadCalendarDataFromJson() {
        if (!isLoggedIn) {
            return;
        }

        String jsonFileName = userAccount + ".json";
        File externalDir = requireContext().getExternalFilesDir(null);
        if (externalDir == null) {
            Log.e("PersonalFragment", "无法访问外部存储目录");
            calendarData = new JSONObject();
            return;
        }

        File jsonFile = new File(externalDir, jsonFileName);
        try {
            if (jsonFile.exists()) {
                BufferedReader reader = new BufferedReader(new FileReader(jsonFile));
                StringBuilder jsonBuilder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    jsonBuilder.append(line);
                }
                reader.close();
                calendarData = new JSONObject(jsonBuilder.toString());
            } else {
                calendarData = new JSONObject();
            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
            calendarData = new JSONObject();
        }
    }

    private void updateCalendarDisplay() {
        tvMonthYear.setText(String.format("%d年%d月", currentYear, currentMonth + 1));
        calendarGrid.removeAllViews();

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, currentYear);
        calendar.set(Calendar.MONTH, currentMonth);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        int firstDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

        for (int i = 0; i < 6 * 7; i++) {
            TextView dayView = new TextView(requireContext());
            dayView.setGravity(Gravity.CENTER);
            dayView.setLayoutParams(new GridLayout.LayoutParams(
                    GridLayout.spec(GridLayout.UNDEFINED, 1.0f),
                    GridLayout.spec(GridLayout.UNDEFINED, 1.0f)
            ));
            dayView.setPadding(8, 8, 8, 8);

            int day = i - firstDayOfWeek + 2;

            if (day >= 1 && day <= daysInMonth) {
                dayView.setText(String.valueOf(day));
                String dateStr = String.format("%d-%02d-%02d", currentYear, currentMonth + 1, day);
                int todayBookcount = 0;

                if (calendarData != null && calendarData.has(dateStr)) {
                    try {
                        todayBookcount = calendarData.getInt(dateStr);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                if (todayBookcount == 0) {
                    dayView.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.calendar_empty));
                } else if (todayBookcount >= 1 && todayBookcount <= 5) {
                    dayView.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.calendar_low));
                } else if (todayBookcount >= 6 && todayBookcount <= 10) {
                    dayView.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.calendar_medium));
                } else if (todayBookcount >= 11) {
                    dayView.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.calendar_high));
                } else {
                    dayView.setBackgroundColor(ContextCompat.getColor(requireContext(), android.R.color.transparent));
                }

                dayView.setOnClickListener(v -> {
                    String dateStrClick = String.format("%d-%02d-%02d", currentYear, currentMonth + 1, day);
                    int todayBookcountClick = 0;
                    if (calendarData != null && calendarData.has(dateStrClick)) {
                        try {
                            todayBookcountClick = calendarData.getInt(dateStrClick);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    Toast.makeText(requireContext(), String.format("%s: 记账次数 %d", dateStrClick, todayBookcountClick), Toast.LENGTH_SHORT).show();
                });
            } else {
                dayView.setVisibility(View.INVISIBLE);
            }

            calendarGrid.addView(dayView);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (sharedPreferences != null) {
            sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
        }
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if (key.equals("isLoggedIn") || key.equals("account") || key.equals("bookCount") || key.equals("username")) {
            isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
            userAccount = sharedPreferences.getString("account", "");
            bookCount = sharedPreferences.getInt("bookCount", 0);
            username = sharedPreferences.getString("username", "");

            if (isLoggedIn) {
                loadUserInfoFromAPI();
            } else {
                updateUIBasedOnLoginStatus();
            }
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        if (isLoggedIn) {
            Calendar calendar = Calendar.getInstance();
            currentYear = calendar.get(Calendar.YEAR);
            currentMonth = calendar.get(Calendar.MONTH);
            updateCalendarDisplay();
        }

        btnPrevMonth.setOnClickListener(v -> {
            if (currentMonth == 0) {
                currentMonth = 11;
                currentYear--;
            } else {
                currentMonth--;
            }
            updateCalendarDisplay();
        });

        btnNextMonth.setOnClickListener(v -> {
            if (currentMonth == 11) {
                currentMonth = 0;
                currentYear++;
            } else {
                currentMonth++;
            }
            updateCalendarDisplay();
        });
    }
}